using UnityEngine;
using System.Collections;

/// \class  gkAbyssalGiantSubmarineLifeAnimationController
/// \brief  The animation controller of the submarine life
[AddComponentMenu("GK/AbyssalGiant/Submarine/gkAbyssalGiantSubmarineLifeAnimationController")]
public class gkAbyssalGiantSubmarineLifeAnimationController : MonoBehaviour 
{
	/// The number of the life the component is on
	public int LifeNumber = 1;
	
	/// Are the life active
	bool m_bLifeActive = true;
	
	/// The life component
	private gkLifeComponent m_rLifeComponent;
	
	/// The appear on event component
	private gkAppearOnEvent m_rAppearOnEvent;
	
	/// \brief  Called just after the game begin to play
    void Start()
    {
		// Get the appear on event component
		m_rAppearOnEvent = GetComponent<gkAppearOnEvent>();
	}
	
	/// \brief  Called when the component is enabled
	void OnEnable() 
	{
		// Grab the life component of the hierarchy the life is on
		m_rLifeComponent = transform.root.GetComponentInChildren<gkLifeComponent>();
		
		// Listen the shock event of the owner
		m_rLifeComponent.GetComponent<gkEventComponent>().AddEventHandler(gkLifeEvent.LifeLoss, HandleLifeLossEvent);
	}
	
	/// \brief  Called when the component is disabled
	void OnDisable() 
	{	
		// Remove the shock event of the owner
		m_rLifeComponent.GetComponent<gkEventComponent>().RemoveEventHandler(gkLifeEvent.LifeLoss, HandleLifeLossEvent);
	}
	
	/// \brief  Called when the component is enabled
	void OnLifeAnimationEnd() 
	{
		// Notify if it remains only one life
		if(LifeNumber == 2)
		{
			m_rLifeComponent.GetComponent<gkEventComponent>().RaiseEvent(gkAbyssalGiantLifeEvent.LastLife);
		}
	}
	
	/// \brief  Handle the life loss event
	void HandleLifeLossEvent(Object m_rEvent)
	{
		if(m_bLifeActive)
		{
			// If the number of life is inferior to the life number represented
			// by this game object
			// play the disparition animation
			if(m_rLifeComponent.GetLife() < LifeNumber)
			{
				m_bLifeActive = false;
				animation.Play("Life_Destroy");
				m_rAppearOnEvent.enabled = false;
			}
		}
	}
}